package org.examcity.domain.jpa;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.examcity.domain.GenericRespository;
import org.examcity.util.ReflectionUtil;
import org.springframework.transaction.annotation.Transactional;

@Transactional(readOnly = true)
@SuppressWarnings("unchecked")
public abstract class GenericRepositoryImpl<T, ID> implements GenericRespository<T, ID> {

	@PersistenceContext
	protected EntityManager em;

	protected Class<T> entityClass;

	public GenericRepositoryImpl() {
		this.entityClass = (Class<T>) ReflectionUtil.getParameterType(getClass(), 0);
	}

	public Class<T> getEntityClass() {
		return entityClass;
	}

	public List<T> findAll() {
		return (List<T>) em.createQuery("from " + entityClass.getName()).getResultList();
	}

	public T find(ID id) {
		return em.find(entityClass, id);
	}

	@Transactional(readOnly = false)
	public void persist(T v) {
		em.persist(v);
	}

	@Transactional(readOnly = false)
	public T merge(T v) {
		return em.merge(v);
	}

	@Override
	public void flush() {
		em.flush();
	}

	@Override
	public void refresh(T v) {
		em.refresh(v);
	}

	@Transactional(readOnly = false)
	@Override
	public void remove(T v) {
		em.remove(v);
	}

}
